package com.zlb.app.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.zlb.app.common.constant.Constants;
import com.zlb.app.common.entity.R;
import com.zlb.app.common.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Desc
 * @Author zWX1367238
 * @Date 2024-08-21 15:08:37
 **/
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private SecurityProperties securityProperties;

    private List<String> whiteUrls;

    @PostConstruct
    public void init() {
        // 初始化白名单,避免每次重新构造
        this.whiteUrls = securityProperties.getWhiteUrls().stream().map(item -> Constants.API_PREFIX + item).collect(Collectors.toList());
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String token = request.getHeader(Constants.TOKEN_NAME);
        // TODO: 2024/8/21 解析token
        if (whiteUrls.contains(requestURI)) {
            // 白名单,直接放行
            return true;
        }
        if (StrUtil.isEmpty(token)) {
            // render(response, R.fail(401, "请先登录!"));
        }
        // TODO: 2024/8/21 验证token是否真实有效

        return true;
    }

    private void render(HttpServletResponse response, R<?> r) throws Exception {
        response.setContentType(Constants.APPLICATION_JSON);
        OutputStream out = response.getOutputStream();
        String str = JSON.toJSONString(r);
        out.write(str.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }

}
